package com.lzc.redis.redis;

import com.lzc.redis.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class RedisService {
    @Autowired
    JedisPool jedisPool;

    /**
     * 设置对象，不过期
     */
    public <T> boolean set(String key, Object object) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String str = JsonUtil.toJson(object);
            jedis.set(key, str);
            return true;
        } finally {
            returnToPool(jedis);
        }
    }

    /**
     * 去除对象，time为过期时间，单位为妙
     *
     * @param key
     * @param object
     * @param time
     * @param <T>
     * @return
     */
    public <T> boolean set(String key, Object object, int time) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String str = JsonUtil.toJson(object);
            jedis.set(key, str);
            jedis.expire(key, time);
            return true;
        } finally {
            returnToPool(jedis);
        }
    }

    /**
     * 获取当个对象
     */
    public <T> T get(String key, Class<T> clazz) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String str = jedis.get(key);
            // 判断是否为空
            if (str == null || str.length() == 0) {
                return null;
            }
            T t = JsonUtil.toBean(clazz, str);
            return t;
        } finally {
            returnToPool(jedis);
        }
    }

    private void returnToPool(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
}
